package com.lingxu.base.system.orgManage.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lingxu.base.common.api.vo.Result;
import com.lingxu.base.common.util.UUID32Generator;
import com.lingxu.base.system.manage.entity.SysOrg;
import com.lingxu.base.system.manage.entity.SysUser;
import com.lingxu.base.system.orgManage.dto.OrgParamsDto;
import com.lingxu.base.system.orgManage.dto.Supervise;
import com.lingxu.base.system.orgManage.mapper.SystemOrgManageMapper;
import com.lingxu.base.system.orgManage.model.SysOrgCompany;
import com.lingxu.base.system.orgManage.service.SystemOrgManageService;
import com.lingxu.base.system.orgManage.vo.SuperviseVO;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Title: SystemOrgManageServiceImpl
 * @Package: com.lingxu.base.system.orgManage.service.impl
 * @Author: ysj闫世杰
 * @Email: 1105324813@qq.com
 * @Date: Created in 2022/3/1 15:00
 * @Description:
 * @Version: 1.0.0
 */
@Service
public class SystemOrgManageServiceImpl implements SystemOrgManageService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SystemOrgManageMapper systemOrgManageMapper;

    /**
     * @Author ysj闫世杰
     * @Description 查询地区
     * @Date 2022/3/3 14:46
     * @Param: code
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result findAreaByCode(String code) {
        try {
            return Result.ok(systemOrgManageMapper.findAreaByCode(code),"查询成功");
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }

    @Override
    public Result findParentId(String id) {
        try {
            return Result.ok(systemOrgManageMapper.findParentId(id),"查询成功");
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }
    /**
     * @Author ysj闫世杰
     * @Description
     * @Date 2022/4/20 17:43
     * @Param: id
     * @return java.lang.String
     **/
    @Override
    public String findAreaName(String id) {
        try {
            return systemOrgManageMapper.findAreaName(id);
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return null;
        }
    }

    /**
     * @Author ysj闫世杰
     * @Description 查询所有的单位名称
     * @Date 2022/3/7 17:55
     * @Param:
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result findAllOrg(String id) {
        try {
            return Result.ok(systemOrgManageMapper.findChildOrg(id),"查询成功");
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }

    /**
     * @Author ysj闫世杰
     * @Description 新增单位部门信息
     * @Date 2022/3/1 15:46
     * @Param: sysOrg
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result addNewOrganizeData(OrgParamsDto dto) {
       try {
           SysOrg sysOrg = new SysOrg();
           Date date = new Date();
           sysOrg.setCreateTime(date);
           sysOrg.setUpdateTime(date);
           String id = UUID32Generator.generate();
           sysOrg.setId(id);
           sysOrg.setUpdateBy(sysOrg.getCreateBy());
           sysOrg.setSimpleName(dto.getSimpleName());
           sysOrg.setName(dto.getName());
           sysOrg.setAddress(dto.getAddress());
           sysOrg.setOrgLevel(dto.getOrgLevel());
           sysOrg.setDwlx(dto.getDwlx());
           sysOrg.setLinkPerson(dto.getLinkPerson());
           sysOrg.setPid(dto.getPid());
           sysOrg.setPName(dto.getPname());
           sysOrg.setTelephone(dto.getTelephone());
           //如果存在pid说明是存在父级节点，level在原来的基础上+1
           if(!StringUtils.isEmpty(sysOrg.getPid())){
               Map map = systemOrgManageMapper.findOrganizeDataById(sysOrg.getPid());
               String orgLevel = (String) map.get("ORG_LEVEL");
               int level = Integer.parseInt(orgLevel);
               level++;
               sysOrg.setOrgLevel(level + "");
           }
           //查询最大的sort排序值
           int sort = systemOrgManageMapper.findMaxSortValue();
           sort++;
           sysOrg.setSort(sort);
           systemOrgManageMapper.addNewOrganizeData(sysOrg);
           //部门关联监督单位
           if(dto.getSupervise() != null && dto.getSupervise().size() > 0){
               List<SysOrgCompany> data = new ArrayList<>();
               for (int i = 0; i < dto.getSupervise().size(); i++) {
                   SysOrgCompany sysOrgCompany = new SysOrgCompany();
                   sysOrgCompany.setId(UUID32Generator.generate());
                   String supId = dto.getSupervise().get(i).getSupId();
                   sysOrgCompany.setCompId(supId);
                   String name = systemOrgManageMapper.findName(supId);
                   sysOrgCompany.setCompName(name);
                   sysOrgCompany.setOrgId(id);
                   sysOrgCompany.setTypes(dto.getSupervise().get(i).getTypes());
                   sysOrgCompany.setUpdateTime(date);
                   sysOrgCompany.setCreateTime(date);
                   sysOrgCompany.setUpdateBy(sysOrg.getCreateBy());
                   data.add(sysOrgCompany);
               }
               systemOrgManageMapper.addOrgCompanyData(data);
           }
           return Result.ok("操作成功");
       }catch (Exception e){
           logger.error("新增单位部门信息异常:",e);
           return Result.error("新增单位部门信息异常");
       }
    }

    /**
     * @Author ysj闫世杰
     * @Description 查询树形结构
     * @Date 2022/3/2 10:23
     * @Param: id
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result findOrgManageTree(String id) {
        try {
            return Result.ok(systemOrgManageMapper.findOrgManageTree(id),"查询成功");
        }catch (Exception e){
            logger.error("查询单位树形结构异常：",e);
            return Result.error("查询单位树形结构异常");
        }
    }


    /**
     * @Author ysj闫世杰
     * @Description
     * @Date 2022/4/21 17:51
     * @Param: id
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result findOrgManagePersonTree(String id) {
        try {
            return Result.ok(systemOrgManageMapper.findOrgManagePersonTree(id),"查询成功");
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }

    @Override
    public Result findOrgManagePersonList(Integer page, Integer limit,String id) {
        try {
            IPage<SysUser> pageInfo = new Page<>(page,limit);
            Page<SysUser> orgManagePersonList = systemOrgManageMapper.findOrgManagePersonList(pageInfo,id);
            return Result.ok(orgManagePersonList,"查询成功");
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }



    /**
     * @Author ysj闫世杰
     * @Description 修改单位部门信息
     * @Date 2022/3/2 10:14
     * @Param: sysOrg
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result updateOrganizeData(OrgParamsDto dto) {
        try {
            SysOrg sysOrg = new SysOrg();
            Date date = new Date();
            sysOrg.setUpdateTime(date);
            sysOrg.setId(dto.getId());
            sysOrg.setName(dto.getName());
            sysOrg.setAddress(dto.getAddress());
            sysOrg.setSimpleName(dto.getSimpleName());
            sysOrg.setOrgLevel(dto.getOrgLevel());
            sysOrg.setDwlx(dto.getDwlx());
            sysOrg.setLinkPerson(dto.getLinkPerson());
            sysOrg.setPid(dto.getPid());
            sysOrg.setPName(dto.getPname());
            sysOrg.setTelephone(dto.getTelephone());
            int i = systemOrgManageMapper.updateOrganizeData(sysOrg);
            if(i > 0){
                systemOrgManageMapper.deleteSupervise(sysOrg.getId());
                //部门关联监督单位
                if(dto.getSupervise() != null && dto.getSupervise().size() > 0){
                    List<SysOrgCompany> data = new ArrayList<>();
                    for (Supervise sup : dto.getSupervise()) {
                        SysOrgCompany sysOrgCompany = new SysOrgCompany();
                        sysOrgCompany.setId(UUID32Generator.generate());
                        String supId = sup.getSupId();
                        sysOrgCompany.setCompId(supId);
                        String name = systemOrgManageMapper.findName(supId);
                        sysOrgCompany.setCompName(name);
                        sysOrgCompany.setOrgId(dto.getId());
                        sysOrgCompany.setTypes(sup.getTypes());
                        sysOrgCompany.setUpdateTime(date);
                        sysOrgCompany.setCreateTime(date);
                        sysOrgCompany.setUpdateBy(sysOrg.getCreateBy());
                        data.add(sysOrgCompany);
                    }
                    systemOrgManageMapper.addOrgCompanyData(data);
                }
                return Result.ok("操作成功");
            }
            return Result.error("操作失败");
        }catch (Exception e){
            logger.error("修改单位部门信息异常:",e);
            return Result.error("修改单位部门信息异常");
        }
    }

    /**
     * @Author ysj闫世杰
     * @Description 根据id查询单位信息
     * @Date 2022/3/2 11:07
     * @Param: id
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result findOrganizeDataById(String id) {
        try {
            Map data = systemOrgManageMapper.findOrganizeDataById(id);
            List<SuperviseVO> supList = systemOrgManageMapper.findSuperviseCompanyList(id);
            Map<String, List<SuperviseVO>> collect = supList.stream().collect(Collectors.groupingBy(SuperviseVO::getTypes));
            data.put("dataList",collect);
            return Result.ok(data,"查询成功");
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }

    /**
     * @Author ysj闫世杰
     * @Description 删除单位信息
     * @Date 2022/3/2 10:23
     * @Param: id
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result deleteOrganizeData(String id) {
        try {
            Integer childNodes = systemOrgManageMapper.findChildNodes(id);
            if(childNodes > 0){
                return Result.error("该组织下存在其他组织无法删除，请删除其下面组织后重试。");
            }
            Integer user = systemOrgManageMapper.findUserByOrgId(id);
            if(user > 0){
                return Result.error("该组织下存在用户无法删除，请删除其下面用户后重试。");
            }
            int i = systemOrgManageMapper.deleteOrganizeData(id);
            if(i > 0){
                systemOrgManageMapper.deleteSupervise(id);
                return Result.ok("操作成功");
            }
            return Result.error("操作失败");
        }catch (Exception e){
            logger.error("删除单位信息异常：",e);
            return Result.error("删除单位信息异常");
        }
    }

    /**
     * @Author ysj闫世杰
     * @Description 查询部门列表
     * @Date 2022/6/16 19:01
     * @Param: page
     * @Param: limit
     * @Param: id
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result findChildOrgList(Integer page, Integer limit, String id) {
        try {
            IPage<SysOrg> pageInfo = new Page<>(page,limit);
            Page<SysOrg> data = systemOrgManageMapper.findChildOrgList(pageInfo,id);
            return Result.ok(data,"查询成功");
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }


    /**
     * @Author ysj闫世杰
     * @Description
     * @Date 2022/6/20 16:24
     * @Param: sort
     * @Param: type
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    @Transactional
    public Result moveTo(String id,Integer sort, String type) {
        //获取要上移、下移的那条数据的信息
        SysOrg sysOrg = systemOrgManageMapper.selectById(id);
        SysOrg sysOrgIndex ;
        if("-1".equals(type)){
            //查询下一条记录
            sysOrgIndex = systemOrgManageMapper.moveDown(sysOrg.getSort());
        }else {
            //查询上一条记录
            sysOrgIndex = systemOrgManageMapper.moveUp(sysOrg.getSort());
        }
        if(sysOrgIndex == null){
            return Result.error("无法继续移动位置");
        }
        //交换两条记录的sort值
        Integer temp = sysOrg.getSort();
        sysOrg.setSort(sysOrgIndex.getSort());
        sysOrgIndex.setSort(temp);
        //更新到数据库
        int i = systemOrgManageMapper.updateSort(sysOrg.getId(), sysOrg.getSort());
        if(i > 0){
            int ii = systemOrgManageMapper.updateSort(sysOrgIndex.getId(),sysOrgIndex.getSort());
            if(ii > 0){
                return Result.ok("操作成功");
            }
        }
        return Result.error("操作失败");
    }
}
